package com.flycms.module.qasystem.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import com.flycms.module.comment.model.OptionCount;

/**
 *
 * <br/>Copyright 2020
 * <br/>All rights reserved
 * @author 沁言訫語
 * @version 2020年3月9日
 * @Date 2020年3月9日
 */

public class QandAWeekCache {

    public static ConcurrentHashMap<String, OptionCount> optionCountCache = new ConcurrentHashMap<>();
    
    private final static String QUESTION_KEY_PRE = "QUESTION_";
    
//    private final static String ANSWER_KEY_PRE = "ANSWER_";
    
    public static void updateQuestionOptionCache(Long contentId, OptionCount op) {
        String key = QUESTION_KEY_PRE + contentId;
        optionCountCache.put(key, op);
    }
    
    public static List<Long> getMaxBrowsedAndUpCountQuestionIds() {
        List<OptionCount> opList = new ArrayList<>();
        for (String key : optionCountCache.keySet()) {
            opList.add(optionCountCache.get(key));
        }
        opList = sort(opList);
        List<Long> ids = new ArrayList<>(opList.size());
        for (OptionCount o : opList) {
            ids.add(o.getId());
        }
        return ids;
    }
    
    public static void removeKey(Long contentId) {
        optionCountCache.remove(QUESTION_KEY_PRE + contentId);
    }
    
    public static List<OptionCount> sort(List<OptionCount> opList) {
        Collections.sort(opList, new Comparator<OptionCount>() {

            @Override
            public int compare(OptionCount o1, OptionCount o2) {
                if (o1.getBrowsedCount() > o2.getBrowsedCount()) {
                    return -1;
                }
                if (o1.getBrowsedCount() == o2.getBrowsedCount()) {
                    if (o1.getUpCount() >= o2.getUpCount()) {
                        return -1;
                    } else {
                        return 1;
                    }
                }
                return 1;
            }
            
        });
        return opList;
    }
    
    public static void main(String[] args) {
        List<OptionCount> list = new ArrayList<>();
        OptionCount op1 = new OptionCount(1L, 1, 0, 0, 0, 12);
        list.add(op1);
        OptionCount op2 = new OptionCount(2L, 2, 0, 0, 0, 12);
        list.add(op2);
        OptionCount op3 = new OptionCount(3L, 1, 0, 0, 0, 1);
        list.add(op3);
        OptionCount op4 = new OptionCount(4L, 1, 0, 0, 0, 14);
        list.add(op4);
        OptionCount op5 = new OptionCount(5L, 5, 0, 0, 0, 14);
        list.add(op5);
        list = sort(list);
        for (OptionCount o : list) {
            System.out.println(o.getBrowsedCount() + " -;-" + o.getUpCount());
        }
    }
    
}
